﻿
using NModbus;
using NModbus.Serial;
using System.Diagnostics;
using System.IO.Ports;
using System;

namespace LeaderCCSLaserUI.Services
{
    public class ServoModbusService : IServoModbusService
    {
        public bool Connected { get; set; }
        SerialPort serialPort = new SerialPort();
        IModbusMaster master;
        private object _lock1 = new object();
        public void Close()
        {
            try
            {
                master.Dispose();
                serialPort.Close();
                serialPort.Dispose();
            }
            catch { }
        }

        public bool Connect(string _portName)
        {
            Connected = false;
            try
            {
                if (this.serialPort.IsOpen)
                {
                    Debug.WriteLine($"伺服串口{_portName}已打开");
                    return false;
                }
                else
                {
                    this.serialPort.PortName = _portName;
                    serialPort.BaudRate = 19200;
                    serialPort.DataBits = 8;
                    serialPort.Parity = Parity.Even;
                    serialPort.StopBits = StopBits.One;
                    this.serialPort.Open();
                    this.serialPort.DiscardInBuffer();
                    this.serialPort.DiscardOutBuffer();
                    this.serialPort.WriteTimeout = 500;
                    this.serialPort.ReadTimeout = 500;
                    var factory = new ModbusFactory();
                    master = factory.CreateRtuMaster(serialPort);
                    Connected = true;
                    return true;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return false;
        }

        public int ReadInovance(byte station)
        {
            object @lock = this._lock1;
            lock (@lock)
            {
                ushort[] r = master.ReadHoldingRegisters(station, 0x0B07, 2);//H0B-07 绝对位置计数器（32位）H05-30参数写6，清零
                return Convert.ToInt32(r[1].ToString("X4") + r[0].ToString("X4"), 16);
            }
        }
    }
}
